package com.example.demo.controller;


import com.example.demo.model.result;
import com.example.demo.services.UserHeaderService;
import com.example.demo.services.uploadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;


//crossorigin允许跨域 不要一直用前端跨域 用后端也要学习写跨域了

@RestController
@CrossOrigin
public class uplodController {

    @Autowired
    private uploadService uploadService;

    @Autowired
    private UserHeaderService userHeaderService;


    @PostMapping("/upload/file")
    @ResponseBody
    public String upload(@RequestParam("file") MultipartFile multipartFile, HttpServletRequest request){
        if(multipartFile.isEmpty()){
            return "文件有误";
        }
        //1:获得用户指定的文件夹，问这个文件夹为什么要从页面上传递呢？
        //原因是:做隔离 不同业务，不同文件放到不同的目录
        String dir = request.getParameter("dir");

        return uploadService.uplodImg(multipartFile,dir);
    }

    SimpleDateFormat sdf=new SimpleDateFormat("yyyy/MM/dd");

    @PostMapping("/upload/two")
    public Map<String,Object> fileupload(MultipartFile file,HttpServletRequest req){
        Map<String,Object> result=new HashMap<>();
        String originName=file.getOriginalFilename();
        if(!originName.endsWith(".png")){
            result.put("status","error");
            result.put("msg","文件类型不对");
            return result;
        }
        String format=sdf.format(new Date());

        String realPath=req.getServletContext().getRealPath("/")+format;
        File folder=new File(realPath);
        if(!folder.exists()){
            folder.mkdirs();
        }
        String newName= UUID.randomUUID().toString()+".png";
        try {
            file.transferTo(new File(folder,newName));
            String url= req.getScheme()+"://"+req.getServerName()+":"+req.getServerPort()+"/"+format+newName;
            result.put("status","success");
            result.put("msg","上传成功");
            result.put("url",url);
        } catch (IOException e) {
            e.printStackTrace();
            result.put("status","400");
            result.put("msg",e.getMessage());
        }
        return result;
    }


    /**
     * 上传文件带params参数 指定把文件上传到哪个文件夹
     * @param file 文件信息
     * @param req 可以通过getParameter获取传输的params 参数 信息
     * @return
     */
    @PostMapping("/upload/all")
    public Map<String,Object> fileall(MultipartFile file,HttpServletRequest req){
        Map<String,Object> result=new HashMap<>();
        String name=file.getOriginalFilename();
        String dir=req.getParameter("dir");
        String imgName=req.getParameter("imgname");

        //判断文件的后缀名 也就是 文件的类型
        if(!name.endsWith(".png")){
            result.put("status","400");
            result.put("msg","文件格式不正确");
            return result;
        }
        //判断是否存在对应的文件夹
        File targetFile=new File("E:\\epidemic\\epidemic\\src\\"+dir);
        try {
            if(!targetFile.exists()){
                targetFile.mkdirs();
            }
            //指定路径然后用file类new 一个不然无法写入
            String filepath="E:\\epidemic\\epidemic\\src\\"+dir+"\\";
            File dest=new File(filepath+imgName);
            file.transferTo(dest);
           result.put("status","200");
           result.put("msg","上传成功");
           if(imgName!=null) {
               //字符串截取小数点前的位数
               int index = imgName.indexOf(".");
               String intNumber = imgName.substring(0,index);
               userHeaderService.inserHeader(intNumber, intNumber);
           }
           return result;
        } catch (IOException e) {
            e.printStackTrace();
            result.put("status","400");
            result.put("msg",e.getMessage());
            return result;
        }
    }

    @PostMapping("/upload/teacher")
    public Map<String,Object> teacher(@RequestBody MultipartFile file,HttpServletRequest request){
        Map<String,Object> test=new HashMap<>();
        String name=file.getOriginalFilename();
        String dir=request.getParameter("dir");
        String teacherId=request.getParameter("teacherId");
        //将照片修改成对应用户的名称 改头像 覆盖原来照片
        String newName=teacherId+".png";
        if(!name.endsWith(".png")){
            test.put("status","400");
            test.put("msg","文件格式不对");
            return test;
        }
        File targetFile=new File("E:\\epidemic\\epidemic\\src\\"+dir);
        try {
            if(!targetFile.exists()){
                targetFile.mkdirs();
            }
            String path="E:\\epidemic\\epidemic\\src\\"+dir+"\\";
            //重写文件名称 输入
            File dest1=new File(path+newName);
            file.transferTo(dest1);
            test.put("status","200");
            test.put("msg","上传成功");
            return test;
        } catch (Exception e){
            e.printStackTrace();
            test.put("status","400");
            test.put("msg",e.getMessage());
            return test;
        }

    }


}
